package com.yaozheng.vocationaltraining.dialog.paper;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.widget.PopupWindow;

import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.activity.BaseActivity;
import com.yaozheng.vocationaltraining.dialog.interfaces.BaseDialogEventProcess;
import com.yaozheng.vocationaltraining.fragment.BaseFragment;
import com.yaozheng.vocationaltraining.utils.LogUtils;
import com.yaozheng.vocationaltraining.view.paper.ExamHelpView;
import com.yaozheng.vocationaltraining.view.paper.ExamHelpView_;

import android.view.ViewGroup.LayoutParams;

/**
 * 考试学习卡帮助
 */
public class ExamHelpPopupWindow implements BaseDialogEventProcess {
    PopupWindow popupWindow;

    BaseFragment baseFragment;

    BaseActivity baseActivity;

    ExamHelpView examHelpView;


    public ExamHelpPopupWindow(BaseFragment baseFragment) {
        this.baseFragment = baseFragment;
        this.baseActivity = baseFragment.getBaseActivity();

    }

    public ExamHelpPopupWindow(BaseActivity baseActivity) {
        this.baseActivity = baseActivity;

    }

    public void show(View anchor) {
        if (popupWindow == null) {
            int width = anchor.getWidth();
            LogUtils.println("宽度" + width);

            examHelpView = ExamHelpView_.build(baseActivity);
            examHelpView.setBaseDialogEventProcess(this);
            if (width > 0) {
                examHelpView.setChildWidth(width);
            }
            popupWindow = new PopupWindow(examHelpView,
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
            popupWindow.setTouchable(true);
            // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
            // 我觉得这里是API的一个bug
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        }
        popupWindow.showAsDropDown(anchor);


    }

    /**
     * 是否显示
     *
     * @return
     */
    public boolean isShowing() {
        if (popupWindow != null) {
            return popupWindow.isShowing();
        } else {
            return false;
        }
    }

    /**
     * 关闭
     */
    public void cancel() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }

    @Override
    public void runMethod(String methodName) {
        cancel();
        if (baseFragment != null) {
            baseFragment.runMethod(methodName);
        } else {
            if (baseActivity != null) {
                baseActivity.runMethod(methodName);
            }
        }
    }
}
